package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Permission permission) {
        permissionMapper.insert(permission);
    }

    @Override
    public Permission get(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> listAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public void update(Permission permission) {
        permissionMapper.updateByPrimaryKey(permission);
    }

    @Override
    public PageInfo<Permission> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Permission> permissions = permissionMapper.selectForList(qo);
        return new PageInfo<>(permissions);
    }

    @Autowired
    private ApplicationContext ctx; //spring上下文

    @Override
    public void reload() {
        //获取数据库中的所有权限表达式
        List<String> permissions = permissionMapper.selectAllExpression();
        //1.获取所有的controller
        Map<String, Object> map = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = map.values();
        //2.遍历每个controller，获取里面的每个方法
        for (Object controller : controllers) {
            //如果不是cglib代理对象，不往下执行
            if (!AopUtils.isCglibProxy(controller)) {
                continue;
            }
            //controller上如果贴了shiro的注解，shiro就会对该controller进行cglib（继承）代理
            //这时候从容器中获取到的就是代理对象，代理类上无法获取父类上的注解，所以需要先拿父类，再从父类中获取注解
            Class clazz = controller.getClass().getSuperclass();//controller的字节码对象
            Method[] methods = clazz.getDeclaredMethods(); //当前字节码中的方法
            //3.遍历每个方法，判断该方法上是否有贴上自定义注解
            for (Method method : methods) {
                //获取方法上的RequiredPermission
                RequiresPermissions annotation = method.getAnnotation(RequiresPermissions.class);
                if(annotation!=null){
                    //有=>4
                    //4.获取注解上的权限名称，以及权限表达式
                    //方式一：直接从注解中获取
                    String expression = annotation.value()[0]; //department:list
                    //方式二：通过反射的方法生成 Employee
                    //String simpleName = clazz.getSimpleName().replace("Controller","");
                    //uncapitalize方法可以把首字母变为小写 employee
                    //String expression = StringUtils.uncapitalize(simpleName)+":"+method.getName();

                    //判断权限表达式是否已经存在数据库中
                    if(!permissions.contains(expression)){  //["department:list","department:delete"]
                        String name = annotation.value()[1];
                        //5.封装成权限对象
                        Permission permission = new Permission();
                        permission.setName(name);
                        permission.setExpression(expression);
                        //6.把对象插入到数据库中
                        permissionMapper.insert(permission);
                    }
                }
                //没有=>跳过
            }
        }











    }

    @Override
    public List<String> selectExpressionByEmpId(Long employeeId) {
        return permissionMapper.selectExpressionByEmpId(employeeId);
    }
}
